package com.xyoto.community.service.impl;

import com.github.pagehelper.PageHelper;
import com.xyoto.community.cache.CacheInstruction;
import com.xyoto.community.cache.UserCache;
import com.xyoto.community.constant.*;
import com.xyoto.community.dto.*;
import com.xyoto.community.entity.comment.DynamicComment;
import com.xyoto.community.entity.comment.DynamicCommentReply;
import com.xyoto.community.entity.love.DynamicCommentLove;
import com.xyoto.community.entity.love.DynamicCommentReplyLove;
import com.xyoto.community.entity.love.DynamicLove;
import com.xyoto.community.entity.main.*;
import com.xyoto.community.enums.*;
import com.xyoto.community.exception.ExceptionUtils;
import com.xyoto.community.mapper.comment.DynamicCommentMapper;
import com.xyoto.community.mapper.comment.DynamicCommentReplyMapper;
import com.xyoto.community.mapper.love.DynamicCommentLoveMapper;
import com.xyoto.community.mapper.love.DynamicCommentReplyLoveMapper;
import com.xyoto.community.mapper.love.DynamicLoveMapper;
import com.xyoto.community.mapper.main.*;
import com.xyoto.community.mapper.picture.DynamicPictureMapper;
import com.xyoto.community.po.*;
import com.xyoto.community.pojo.DynamicStatistic;
import com.xyoto.community.service.*;
import com.xyoto.community.utils.JwtUtils;
import com.xyoto.community.utils.PageUtils;
import com.xyoto.community.utils.RedisCommonUtils;
import com.xyoto.community.utils.Result;
import com.xyoto.community.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName:   新增动态Service接口实现类
 * Author:      挽风
 * Date:        2020
 * Copyright:   2020 by 挽风1.0版本
 * Description:
 **/

@Service
@Slf4j
public class DynamicServiceImpl implements DynamicService {

    @Resource
    private DynamicMapper dynamicMapper;

    @Resource
    private TopicMapper topicMapper;

    @Resource
    private HttpServletRequest request;

    @Resource
    private FanFollowMapper fanFollowMapper;

    @Resource
    private DynamicPictureMapper dynamicPictureMapper;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Autowired
    private DynamicCommentMapper dynamicCommentMapper;

    @Autowired
    private HotDynamicMapper hotDynamicMapper;

    @Autowired
    private MessageService messageService;

    @Autowired
    private DynamicCommentReplyMapper dynamicCommentReplyMapper;

    @Autowired
    private DynamicLoveMapper dynamicLoveMapper;

    @Autowired
    private DynamicCommentLoveMapper dynamicCommentLoveMapper;

    @Autowired
    private DynamicCommentReplyLoveMapper dynamicCommentReplyLoveMapper;

    @Autowired
    private DynamicForwardMapper dynamicForwardMapper;

    @Resource
    private PictureService pictureService;

    @Resource
    private TopicUserHotService topicUserHotService;

    @Autowired
    private AnonyUserService anonyUserService;

    @Autowired
    private RedisCommonUtils redisCommonUtils;

    @Autowired
    private DynamicCommentReplyTop5ServiceCache dynamicCommentReplyTop5ServiceCache;

    @Autowired
    private UserCacheService userCacheService;

    @Autowired
    private UserTitleService userTitleService;

    @Autowired
    private DynamicCacheService dynamicCacheService;

    @Autowired
    private TopicHotDynamicCacheService topicHotDynamicCacheService;

    @Autowired
    private TopicAllDynamicCacheService topicAllDynamicCacheService;

    @Autowired
    private TopicCacheService topicCacheService;

    @Autowired
    private PictureCacheService pictureCacheService;

    @Autowired
    private UserTitleCacheService userTitleCacheService;



    /**
     * 新增动态评论回复
     *
     * @param saveDynamicCommentReplyDTO
     * @return
     */
    @Override
    @Transactional
    public Result saveDynamicCommentReply(SaveDynamicCommentReplyDTO saveDynamicCommentReplyDTO) {

        // 获取当前用户的id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        if (userId == UserLoginStatus.UN_LOGIN) {
            // 用户未登录
            ExceptionUtils.error(WechatLoginEnum.USER_NOT_LOGIN);
        }

        // 若回复的是回复，则检查动态评论回复是否存在
        DynamicCommentReply targetDynamicCommentReply = null;
        if (saveDynamicCommentReplyDTO.getReplyId() != null) {
            targetDynamicCommentReply = dynamicCommentReplyMapper
                    .selectOneByDynamicCommentReplyId(saveDynamicCommentReplyDTO.getReplyId());
            checkDynamicCommentReplyExist(targetDynamicCommentReply);
        }

        // 根据动态评论id检查动态评论是否存在
        DynamicComment dynamicComment = dynamicCommentMapper
                .selectOneByDynamicCommentId(saveDynamicCommentReplyDTO.getCommentId());
        checkDynamicCommentExist(dynamicComment);
        // 回复的是回复，那么需要判断目标回复与动态评论的关系
        if (saveDynamicCommentReplyDTO.getReplyId() != null
                && targetDynamicCommentReply != null
                && !saveDynamicCommentReplyDTO.getCommentId().equals(targetDynamicCommentReply.getDynamicCommentId())) {
            // 目标回复不属于该条评论
            ExceptionUtils.error(DynamicCommentReplyEnum.DYNAMIC_COMMENT_REPLY_NOT_MATCH_COMMENT);
        }

        // 查询动态是否存在
        Integer dynamicId = dynamicComment.getDynamicId();
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(dynamicId);
        checkDynamicExist(dynamic);

        // 新增动态评论回复
        DynamicCommentReply dynamicCommentReply = new DynamicCommentReply();
        dynamicCommentReply.setDynamicCommentId(dynamicComment.getId());
        dynamicCommentReply.setContent(saveDynamicCommentReplyDTO.getContent());
        dynamicCommentReply.setDeleteStatus(DeleteStatus.NO);
        dynamicCommentReply.setUserId(userId);

        if (saveDynamicCommentReplyDTO.getReplyId() != null) {
            // 是回复评论的回复
            dynamicCommentReply.setTargetDynamicCommentReplyId(saveDynamicCommentReplyDTO.getReplyId());
        }

        Integer insert = dynamicCommentReplyMapper.insertOne(dynamicCommentReply);
        if (insert < DatabaseOperationResult.SUCCESS) {
            ExceptionUtils.error(DynamicCommentReplyEnum.DYNAMIC_COMMENT_REPLY_CREATE_ERROR);
        }
        // 将回复内容和目标回复用户信息进行封装返回
        SaveDynamicCommentReplyVO saveDynamicCommentReplyVO = new SaveDynamicCommentReplyVO();
        saveDynamicCommentReplyVO.setCommentId(dynamicComment.getId());
        saveDynamicCommentReplyVO.setReplyId(dynamicCommentReply.getId());
        saveDynamicCommentReplyVO.setContent(saveDynamicCommentReplyDTO.getContent());
        // 如果是回复回复，则查询回复目标的用户信息
        if (saveDynamicCommentReplyDTO.getReplyId() != null) {
            assert targetDynamicCommentReply != null;
            UserCache userCache = userCacheService.getUserMessageFromUserCacheById(targetDynamicCommentReply.getUserId());
            //从缓存中获取数据
            UserPO userPO = new UserPO(userCache.getId(), userCache.getNickname(), userCache.getAvatarUrl(), userCache.getSignature());
            saveDynamicCommentReplyVO.setTargetReplyUser(userPO);
        }

        // 添加回复到消息表
        //判断是回复的回复还是评论的回复
        Integer targetUserId = targetDynamicCommentReply == null ?
                dynamicComment.getUserId() : targetDynamicCommentReply.getUserId();
        if (saveDynamicCommentReplyDTO.getReplyId() != null) {
            //是回复的回复
            messageService.saveMessage(userId, targetUserId, dynamicCommentReply.getId()
                    , ModuleType.DYNAMIC_COMMENT_REPLY, dynamicCommentReply.getId()
                    , dynamicCommentReply.getTargetDynamicCommentReplyId(), dynamicComment.getId(), dynamicId);
        } else {
            //是评论的回复
            messageService.saveMessage(userId, targetUserId,
                    dynamicCommentReply.getId(), ModuleType.DYNAMIC_COMMENT_REPLY, null
                    , dynamicCommentReply.getId(), dynamicComment.getId(), dynamic.getId());
        }
        //更新动态评论中的回复字段
        if (dynamicComment.getReplyFirstId() == null) {
            if (dynamicComment.getReplySecondId() != null) {
                //第一个回复id为空，第二个回复id不为空，此时要调整顺序
                dynamicComment.setReplyFirstId(dynamicComment.getReplySecondId());
                dynamicComment.setReplySecondId(dynamicCommentReply.getId());
            } else {
                dynamicComment.setReplyFirstId(dynamicCommentReply.getId());
            }
            //如果第一个不为空，第二个为空的时候
        } else if (dynamicComment.getReplySecondId() == null) {
            dynamicComment.setReplySecondId(dynamicCommentReply.getId());
        }
        //更新评论数据信息
        dynamicCommentMapper.updateDynamicCommentById(dynamicComment);

        //给话题下的动态增加活跃值
        //判断该动态是否为私密
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal()) && dynamic.getTopicId() != null) {
            //非私密给该动态加分
            topicHotDynamicCacheService.addTopicHotDynamicScore(dynamic.getTopicId(), dynamic.getId(), DynamicOperateType.DYNAMIC_REPLY);
        }

        //将回复信息存储到缓存中
        dynamicCommentReplyTop5ServiceCache.saveCommentReplyCache(saveDynamicCommentReplyDTO.getCommentId(), dynamicCommentReply.getId());
        // 给用户增加活跃度
        topicUserHotService.addHot(userId, dynamic.getTopicId(), TopicUserHotType.REPLY);

        // 将动态缓存到redis
        dynamicCacheService.saveDynamic2Cache(dynamic, DynamicOperateType.DYNAMIC_REPLY);

        return Result.success(saveDynamicCommentReplyVO);
    }

    /**
     * 新增动态点赞
     *
     * @param saveDynamicLoveDTO
     * @return
     */
    @Override
    @Transactional
    public Result saveDynamicLove(SaveDynamicLoveDTO saveDynamicLoveDTO) {

        // 获取当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        // 判断动态是否存在
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(saveDynamicLoveDTO.getDynamicId());
        checkDynamicExist(dynamic);

        // 判断当前用户是否点赞过该动态
        Integer dynamicId = dynamic.getId();
        DynamicLove dynamicLove = dynamicLoveMapper.selectOneByUserIdAndDynamicId(userId, dynamicId);
        if (dynamicLove != null && dynamicLove.getStatus().equals(LoveStatus.LOVE)) {
            // 当前用户点赞该动态
            ExceptionUtils.error(LoveEnum.DYNAMIC_LOVE_LOVED);
        }
        if (dynamicLove == null) {
            // 当前用户从来未对该动态点赞过
            // 新增点赞记录
            dynamicLove = new DynamicLove();
            dynamicLove.setDynamicId(dynamicId);
            dynamicLove.setUserId(userId);
            dynamicLove.setStatus(DeleteStatus.YES);
            Integer insert = dynamicLoveMapper.insertOne(dynamicLove);
            if (insert < DatabaseOperationResult.SUCCESS) {
                // 保存到数据库失败
                ExceptionUtils.error(DynamicEnum.DYNAMIC_ADD_ERROR);
            }
            //添加消息到消息表
            messageService.saveMessage(userId, dynamic.getUserId(), dynamicLove.getId(), ModuleType.DYNAMIC_LOVE, null
                    , null, null, dynamicId);
        } else {
            // 当前用户之前对该动态评论点赞过，但又取消了，现在又点赞
            dynamicLove.setStatus(LoveStatus.LOVE);
            Integer update = dynamicLoveMapper.updateDynamicLove(dynamicLove);
            if (update < DatabaseOperationResult.SUCCESS) {
                ExceptionUtils.error(DynamicEnum.DYNAMIC_ADD_ERROR);
            }
            //添加消息到消息表
            messageService.saveMessage(userId, dynamic.getUserId(), dynamicLove.getId(), ModuleType.DYNAMIC_LOVE, null,
                    null, null, dynamicId);
        }

        //判断该动态是否为私密,给话题下的热门动态加分
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal()) && dynamic.getTopicId() != null) {
            //非私密给该动态加分
            topicHotDynamicCacheService.addTopicHotDynamicScore(dynamic.getTopicId(), dynamic.getId(), DynamicOperateType.DYNAMIC_LOVE);
        }

        // 给用户增加活跃度
        topicUserHotService.addHot(userId, dynamic.getTopicId(), TopicUserHotType.LOVE);

        // 给动态主人增加活跃度
        topicUserHotService.addHot(dynamic.getUserId(), dynamic.getTopicId(), TopicUserHotType.DYNAMIC_BE_LOVE);

        // 将动态缓存到redis
        dynamicCacheService.saveDynamic2Cache(dynamic, DynamicOperateType.DYNAMIC_LOVE);

        // 更新动态的点赞数
        dynamicCacheService.updateDynamicLoveCountInCache(dynamicLove);

        //新增动态点赞
        userCacheService.addUserDynamicLoveStatus(userId, dynamicId);

        return Result.success();
    }

    /**
     * 根据动态id删除动态
     *
     * @param dynamicId 动态id
     * @return
     */
    @Transactional
    @Override
    public Result removeDynamicById(Integer dynamicId) {
        if (null == dynamicId || dynamicId <= 0) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_ID_ERROR);
        }
        //此条动态主人以及管理员可删此动态，其余用户不可删
        Dynamic dynamic = dynamicMapper.getDynamicById(dynamicId);
        checkDynamicExist(dynamic);
        //获取动态的主人id
        Integer dynamicUserId = dynamic.getUserId();
        //当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        if (!userId.equals(dynamicUserId)) {
            ExceptionUtils.error(DynamicEnum.YOU_NOT_POWER);
        }
        dynamic.setDeleteStatus(DeleteStatus.YES);
        Integer update = dynamicMapper.updateDynamicById(dynamic);
        if (update != OperationStatus.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_DELETE_FAILED);
        }
        //删除热门动态中的动态信息
        Integer integer = hotDynamicMapper.deleteDynamic(dynamicId, dynamic.getTopicId());
        if (integer != DatabaseOperationResult.SUCCESS) {
            log.info("【热门动态中的动态信息删除成功】");
        }
        //删除动态点赞消息、动态评论消息
        List<Short> type = Arrays.asList(MessageConstant.DYNAMIC_LIST);
        messageService.deleteMessageByThirdParentId(dynamicId, type);
        log.info("【消息中与该动态相关的消息删除成功】");

        // 更新redis中的该动态信息
        dynamicCacheService.updateDynamicInCache(dynamic);

        //删除动态缓存中存储的信息
        if (dynamic.getTopicId() != null) {
            topicAllDynamicCacheService.deleteTopicAllDynamicForMakePersonal(dynamic.getTopicId(), dynamic.getId());
            topicHotDynamicCacheService.deleteTopicHotDynamicById(dynamic.getTopicId(), dynamic.getId());
        }
        userCacheService.deleteUserAllDynamicForDeleteDynamic(dynamic.getUserId(), dynamicId);

        // 更新redis中的动态数量
        dynamicCacheService.updateDynamicCountInCache(dynamic);
        //更新图片缓存中的信息
        pictureCacheService.deletePictureIdsFromCache(dynamicId);
        return Result.success();
    }

    /**
     * 根据动态评论id删除动态评论
     *
     * @param dynamicCommentId 动态评论id
     * @return
     */
    @Transactional
    @Override
    public Result removeDynamicCommentByDynamicCommentId(Integer dynamicCommentId) {
        //todo 检验权限 管理员权限未加
        //此条动态主人、此问答评论主人以及管理员可删此评论，其余用户不可删
        if (null == dynamicCommentId || dynamicCommentId <= 0) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_ID_ERROR);
        }
        DynamicComment dynamicComment = dynamicCommentMapper
                .selectOneByDynamicCommentId(dynamicCommentId);
        checkDynamicCommentExist(dynamicComment);
        //获取动态评论主人id
        Integer questionCommentUserId = dynamicComment.getUserId();
        Dynamic dynamic = dynamicMapper
                .selectOneByDynamicId(dynamicComment.getDynamicId());
        checkDynamicExist(dynamic);
        //获取动态主人id
        Integer dynamicUserId = dynamic.getUserId();
        //当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        if (!userId.equals(questionCommentUserId)
                || !userId.equals(dynamicUserId)) {
            ExceptionUtils.error(DynamicEnum.YOU_NOT_POWER);
        }
        dynamicComment.setDeleteStatus(DeleteStatus.YES);
        //删除动态评论
        Integer status = dynamicCommentMapper
                .removeDynamicComment(dynamicComment);
        if (status != OperationStatus.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_DELETED_FAILED);
        }
        //删除评论相关消息
        List<Short> type = Arrays.asList(MessageConstant.DYNAMIC_COMMENT_LIST);
        messageService.deleteMessageBySecondParentId(dynamicCommentId, type);
        //删除缓存中的评论相关记录
        dynamicCommentReplyTop5ServiceCache.deleteCommentReplyCache(dynamicCommentId, null);
        return Result.success();
    }

    /**
     * 删除动态评论回复
     *
     * @param dynamicCommentReplyId 回复id
     * @return
     */
    @Transactional
    @Override
    public Result removeDynamicCommentReply(Integer dynamicCommentReplyId) {
        if (null == dynamicCommentReplyId || dynamicCommentReplyId <= 0) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_REPLY_ID_ERROR);
        }
        //todo 检验权限 管理员权限未加
        //此条动态主人、此动态评论主人、此动态评论回复主人以及管理员可删此回复，其余用户不可删
        //检验此回复是否存在
        DynamicCommentReply dynamicCommentReply = dynamicCommentReplyMapper
                .selectOneByDynamicCommentReplyId(dynamicCommentReplyId);
        checkDynamicCommentReplyExist(dynamicCommentReply);
        //获取此动态评论回复主人id
        Integer replyUserId = dynamicCommentReply.getUserId();
        //检验此评论是否存在
        DynamicComment dynamicComment = dynamicCommentMapper
                .selectOneByDynamicCommentId(dynamicCommentReply.getDynamicCommentId());
        checkDynamicCommentExist(dynamicComment);
        //获取此动态评论主人id
        Integer commentUserId = dynamicComment.getUserId();
        //检验此动态是否存在
        Dynamic dynamic = dynamicMapper
                .selectOneByDynamicId(dynamicComment.getDynamicId());
        checkDynamicExist(dynamic);
        //获取问答主人id
        Integer dynamicUserId = dynamic.getUserId();
        //当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        if (userId.equals(replyUserId)
                || userId.equals(commentUserId)
                || userId.equals(dynamicUserId)) {
            //业务操作
            DynamicCommentReply reply = new DynamicCommentReply();
            reply.setDeleteStatus(DeleteStatus.YES);
            reply.setId(dynamicCommentReplyId);
            reply.setUserId(userId);
            Integer state = dynamicCommentReplyMapper
                    .removeDynamicCommentReply(reply);
            if (state != OperationStatus.SUCCESS) {
                ExceptionUtils.error(DynamicEnum.REPLY_DELETED_FAILED);
            }
            //删除回复相关消息
            //判断是回复的回复还是  评论的回复
            List<Short> type = Arrays.asList(MessageConstant.DYNAMIC_REPLY_LIST);
            if (dynamicCommentReply.getTargetDynamicCommentReplyId() != null && dynamicCommentReply.getTargetDynamicCommentReplyId() > 0) {
                //回复的回复
                messageService.deleteMessageByZeroParentId(dynamicCommentReplyId, type);
            } else {
                //评论的回复
                messageService.deleteMessageByFirstParentId(dynamicCommentReplyId, type);
            }
            return Result.success();
        } else {
            ExceptionUtils.error(QuestionsEnum.NOT_POWER);
        }
        //判断是否需要更新动态评论中的信息
        boolean flag = false;
        if (dynamicCommentReplyId.equals(dynamicComment.getReplyFirstId())) {
            dynamicComment.setReplyFirstId(null);
            flag = true;
        } else if (dynamicCommentReplyId.equals(dynamicComment.getReplySecondId())) {
            dynamicComment.setReplySecondId(null);
            flag = true;
        }
        if (flag) {
            dynamicCommentMapper.updateDynamicCommentById(dynamicComment);
        }
        //删除动态评论回复缓存信息
        dynamicCommentReplyTop5ServiceCache.deleteCommentReplyCache(dynamicComment.getId(), dynamicCommentReplyId);
        return Result.success();
    }

    /**
     * 新增动态评论点赞
     *
     * @param saveDynamicCommentLoveDTO
     * @return
     */
    @Override
    @Transactional
    public Result saveDynamicCommentLove(SaveDynamicCommentLoveDTO saveDynamicCommentLoveDTO) {
        // 获取当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        // 检查动态评论是否存在
        Integer dynamicCommentId = saveDynamicCommentLoveDTO.getDynamicCommentId();
        DynamicComment dynamicComment = dynamicCommentMapper.selectOneByDynamicCommentId(dynamicCommentId);
        checkDynamicCommentExist(dynamicComment);

        // 检查动态评论所属的动态是否存在
        Integer dynamicId = dynamicComment.getDynamicId();
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(dynamicId);
        checkDynamicExist(dynamic);

        // 判断用户是否对该动态评论点赞
        DynamicCommentLove dynamicCommentLove = dynamicCommentLoveMapper.selectOneByUserIdAndDynamicCommentId(userId, dynamicCommentId);
        if (dynamicCommentLove != null && dynamicCommentLove.getStatus().equals(LoveStatus.LOVE)) {
            // 该用户已点赞
            ExceptionUtils.error(LoveEnum.DYNAMIC_COMMENT_LOVE_LOVED);
        }
        if (dynamicCommentLove == null) {
            // 当前用户从来没有对该评论动态点过赞
            // 新增动态评论点赞记录
            dynamicCommentLove = new DynamicCommentLove();
            dynamicCommentLove.setDynamicCommentId(dynamicCommentId);
            dynamicCommentLove.setStatus(LoveStatus.LOVE);
            dynamicCommentLove.setUserId(userId);
            Integer insert = dynamicCommentLoveMapper.insertOne(dynamicCommentLove);
            if (insert < DatabaseOperationResult.SUCCESS) {
                // 保存到数据库失败
                ExceptionUtils.error(LoveEnum.DYNAMIC_COMMENT_LOVE_FAIL);
            }
            //添加到消息表
            messageService.saveMessage(userId, dynamicComment.getUserId(), dynamicCommentLove.getId(),
                    ModuleType.DYNAMIC_COMMENT_LOVE, null, null, dynamicCommentId, dynamicId);
        } else {
            // 当前用户之前对该动态评论点赞过，但又取消了，现在又点赞
            dynamicCommentLove.setStatus(LoveStatus.LOVE);
            Integer update = dynamicCommentLoveMapper.updateDynamicCommentLove(dynamicCommentLove);
            if (update < DatabaseOperationResult.SUCCESS) {
                // 更新到数据库失败
                ExceptionUtils.error(LoveEnum.DYNAMIC_COMMENT_LOVE_FAIL);
            }
            //添加到消息表
            messageService.saveMessage(userId, dynamicComment.getUserId(), dynamicCommentLove.getId(),
                    ModuleType.DYNAMIC_COMMENT_LOVE, null, null, dynamicCommentId, dynamicId);
        }

        //判断该动态是否为私密,给话题下的热门动态加分
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal()) && dynamic.getTopicId() != null) {
            //非私密给该动态加分
            topicHotDynamicCacheService.addTopicHotDynamicScore(dynamic.getTopicId(), dynamic.getId(), DynamicOperateType.DYNAMIC_COMMENT_LOVE);
        }


        // 给用户增加活跃度
        topicUserHotService.addHot(userId, dynamic.getTopicId(), TopicUserHotType.LOVE);

        // 将动态缓存到redis
        dynamicCacheService.saveDynamic2Cache(dynamic, DynamicOperateType.DYNAMIC_LOVE);

        return Result.success();
    }

    /**
     * 检查动态评论是否存在
     *
     * @param dynamicComment
     */
    private void checkDynamicCommentExist(DynamicComment dynamicComment) {
        if (dynamicComment == null) {
            // 动态评论不存在
            ExceptionUtils.error(DynamicCommentEnum.DYNAMIC_COMMENT_NOT_EXIST);
        }
        if (dynamicComment.getDeleteStatus().equals(DeleteStatus.YES)) {
            // 动态评论已被删除
            ExceptionUtils.error(DynamicCommentEnum.DELETED);
        }
    }

    /**
     * 新增动态Web接口
     *
     * @param saveDynamicDTO 动态表单DTO
     * @return 操作状态
     */
    @Override
    @Transactional
    public Result saveDynamic(SaveDynamicDTO saveDynamicDTO) {

        // TODO 文件数量未进行限制
        log.info("=====开始执行新增动态=====");

        // 判断用户是否登录
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        //判断是否匿名
        //获取可匿名的话题列表
        List<Integer> enableAnonyTopicList = Arrays.asList(TopicUserHotType.ENABLE_ANONY_TOPIC);
        Integer topicId = saveDynamicDTO.getTopicId();
        // 如果有topicId，则检查数据库中是否存在该话题
        getTopicIsExistById(topicId);
        //判断参数是否合法
        Dynamic dynamic = new Dynamic();
        if (saveDynamicDTO.getTopicId() == null) {
            dynamic.setTopicId(0);
        }
        Topic topic = null;
        // 如果有话题id，判断话题是否存在
        if (topicId != null) {
            topic = topicMapper.selectOneByTopicId(topicId);
        }

        if (topicId != null && enableAnonyTopicList.contains(topicId)) {
            //属于可以匿名的话题
            //匿名相关属性为空，未选择匿名相关选项
            if (Integer.valueOf(0).equals(saveDynamicDTO.getAnonymousUserId()) || saveDynamicDTO.getAnonymousUserId() == null) {
                log.info("【无匿名相关操作】");
                dynamic.setStatus(AnonymousStatus.NORMAL);
            } else {
                //判断是否为匿名信息中其中一个
                Object anonymousUser = redisCommonUtils.hget(CacheInstruction.ANONYMOUS_USER, saveDynamicDTO.getAnonymousUserId());
                if (anonymousUser == null) {
                    //前端传递的匿名用户id不合法
                    log.info("【匿名id参数不合法】");
                    ExceptionUtils.error(CommonEnum.REQUEST_PARAM_ERROR);
                }
                //匿名用户信息处理
                //加入匿名状态
                dynamic.setStatus(AnonymousStatus.ANONYMOUS);
                dynamic.setAnonymousUserId(saveDynamicDTO.getAnonymousUserId());
            }
        } else {
            //非匿名时的状态
            dynamic.setStatus(AnonymousStatus.NORMAL);
        }

        // 保存动态
        dynamic.setContent(saveDynamicDTO.getContent());
        dynamic.setTopicId(saveDynamicDTO.getTopicId());
        dynamic.setDynamicPlace(saveDynamicDTO.getDynamicPlace());
        // 设置隐私状态、删除状态
        dynamic.setPersonal(DynamicPrivacy.ALL_SHOW);
        dynamic.setDeleteStatus(DeleteStatus.NO);
        dynamic.setUserId(userId);

        Integer integer = dynamicMapper.insertDynamic(dynamic);
        if (integer < DatabaseOperationResult.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_ADD_ERROR);
        }
        log.info("=====结束存储动态=====");


        //更新keyId到图片表
        pictureService.updateBathPictureKeyId(saveDynamicDTO.getGroup(), dynamic.getId());
        log.info("更新keyId完成");
        log.info("=====开始存储动态热度=====");
        // 存储动态热度
        HotDynamic hotDynamic = new HotDynamic();
        hotDynamic.setDynamicId(dynamic.getId());
        hotDynamic.setTopicId(dynamic.getTopicId());
        hotDynamic.setHotCount(0);
        hotDynamic.setCurrentHot(0);
        Integer hot = hotDynamicMapper.insertHotDynamic(hotDynamic);
        if (hot < DatabaseOperationResult.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_HOT_ADD_FAIL);
        }
        log.info("=====结束存储动态热度=====");

        // 给用户增加活跃度
        topicUserHotService.addHot(userId, dynamic.getTopicId(), TopicUserHotType.PUBLISH_DYNAMIC);

        if (topic != null) {
            // 给话题主人加活跃度
            topicUserHotService.addHot(topic.getUserId(), dynamic.getTopicId(), TopicUserHotType.PUBLISH_DYNAMIC_IN_MY_TOPIC);
        }
        //添加到话题下的全部动态列表中
        if (dynamic.getTopicId() != null && Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal())) {
            long timestamp = dynamic.getCreateTime().getTime();
            topicAllDynamicCacheService.saveNewTopicDynamic(dynamic.getTopicId(), dynamic.getId(), timestamp);
        }

        //将动态缓存到用户动态列表中
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal())) {
            userCacheService.addUserAllDynamic(userId, dynamic.getId(), dynamic.getCreateTime().getTime());
        }

        // 将动态缓存到redis中，异步执行
        dynamicCacheService.saveDynamic2Cache(dynamic, null);

        // 更新缓存中的动态数量
        dynamicCacheService.updateDynamicCountInCache(dynamic);

        return Result.success();
    }


    /**
     * 根据话题id查询话题是否存在
     *
     * @param topicId
     */
    private void getTopicIsExistById(Integer topicId) {
        if (topicId != null) {
            // 大于0则进行查询
            Integer topicIsExistById = topicMapper.getTopicIsExistById(topicId);
            if (topicIsExistById != 1) {
                ExceptionUtils.error(DynamicEnum.DYNAMIC_ADD_TOPIC_NOT_NULL);
            }
        }
    }

    /**
     * 修改动态Web接口
     *
     * @param updateDynamicDTO 修改后的动态表单DTO
     * @return 修改状态
     */
    @Override
    @Transactional
    public Result updateDynamic(UpdateDynamicDTO updateDynamicDTO) {
        // TODO 文件数量未进行限制
        log.info("=====开始执行修改动态=====");

        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 判断动态所属话题是否存在
        getTopicIsExistById(updateDynamicDTO.getTopicId());

        // 判断动态是否存在以及所属用户是否对应
        Dynamic currDynamic = dynamicMapper.selectOneByDynamicId(updateDynamicDTO.getId());
        if (currDynamic == null) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_NOT_EXIST);
        }

        if (!userId.equals(currDynamic.getUserId())) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_UPDATE_NOT_PER);
        }

        // 存储动态
        BeanUtils.copyProperties(updateDynamicDTO, currDynamic);
        if (updateDynamicDTO.getTopicId() == null) {
            currDynamic.setTopicId(0);
        }

        Integer update = dynamicMapper.updateDynamicById(currDynamic);
        if (update < DatabaseOperationResult.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_UPDATE_FAIL);
        }

        pictureService.updateBathPictureKeyId(updateDynamicDTO.getGroup(), currDynamic.getId());
        log.info("图片修改成功");
        log.info("=====结束存储动态=====");

        // 将动态缓存到redis
        dynamicCacheService.saveDynamic2Cache(currDynamic, null);

        return Result.success();
    }

    /**
     * 取消动态点赞
     *
     * @param dynamicId 动态id
     * @return
     */
    @Override
    @Transactional
    public Result removeDynamicLoveByDynamicId(Integer dynamicId) {
        if (null == dynamicId || dynamicId <= 0) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_ID_ERROR);
        }
        // 判断动态是否存在
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(dynamicId);
        checkDynamicExist(dynamic);
        //检验动态点赞是否存在
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        DynamicLove dynamicLove = dynamicLoveMapper.selectOneByUserIdAndDynamicId(userId, dynamicId);
        if (null == dynamicLove) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_NOT_LOVE);
        }
        if (dynamicLove.getStatus().equals(DeleteStatus.NO)) {
            // 动态点赞已取消
            ExceptionUtils.error(DynamicEnum.LOVE_IS_REMOVE);
        }
        //取消动态点赞操作
        dynamicLove.setStatus(DeleteStatus.NO);
        Integer state = dynamicLoveMapper.updateDynamicLove(dynamicLove);
        if (state != OperationStatus.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DELETE_DYNAMIC_LOVE_FAILED);
        }
        //取消用户动态点赞
        userCacheService.cancelUserDynamicLove(userId, dynamicId);
        //删除点赞消息
        messageService.deleteMessage(userId, dynamicLove.getId(), ModuleType.DYNAMIC_LOVE);

        // 更新动态的点赞数
        dynamicCacheService.updateDynamicLoveCountInCache(dynamicLove);
        return Result.success();
    }

    /**
     * 取消动态评论点赞
     *
     * @param dynamicCommentId 动态评论id
     * @return
     */
    @Override
    @Transactional
    public Result removeDynamicCommentLoveByDynamicCommentId(Integer dynamicCommentId) {
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        if (null == dynamicCommentId || dynamicCommentId <= 0) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_ID_ERROR);
        }
        //检验动态评论是否存在
        DynamicComment dynamicComment = dynamicCommentMapper.
                selectOneByDynamicCommentId(dynamicCommentId);
        checkDynamicCommentExist(dynamicComment);
        //检验动态是否存在
        Dynamic dynamic = dynamicMapper.
                getDynamicById(dynamicComment.getDynamicId());
        checkDynamicExist(dynamic);
        //检验动态点赞是否存在
        DynamicCommentLove dynamicCommentLove = dynamicCommentLoveMapper.
                selectOneByUserIdAndDynamicCommentId(userId, dynamicCommentId);
        if (null == dynamicCommentLove) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_NOT_LOVE);
        }
        if (dynamicCommentLove.getStatus().equals(DeleteStatus.NO)) {
            // 动态评论点赞已取消
            ExceptionUtils.error(DynamicEnum.LOVE_IS_REMOVE);
        }
        dynamicCommentLove.setStatus(DeleteStatus.NO);
        Integer state = dynamicCommentLoveMapper.
                updateDynamicCommentLove(dynamicCommentLove);
        if (state != OperationStatus.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DELETE_DYNAMIC_COMMENT_LOVE_FAILED);
        }
        //删除点赞消息
        messageService.deleteMessage(userId, dynamicCommentLove.getId(), ModuleType.DYNAMIC_COMMENT_LOVE);
        return Result.success();
    }

    /**
     * 新增动态评论回复点赞
     *
     * @param saveDynamicCommentReplyLoveDTO
     * @return
     */
    @Override
    @Transactional
    public Result saveDynamicCommentReplyLove(SaveDynamicCommentReplyLoveDTO saveDynamicCommentReplyLoveDTO) {
        // 获取当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 检查动态评论回复是否存在
        Integer dynamicCommentReplyId = saveDynamicCommentReplyLoveDTO.getDynamicCommentReplyId();
        DynamicCommentReply dynamicCommentReply = dynamicCommentReplyMapper.selectOneByDynamicCommentReplyId(dynamicCommentReplyId);
        checkDynamicCommentReplyExist(dynamicCommentReply);


        // 检查动态评论是否存在
        Integer dynamicCommentId = dynamicCommentReply.getDynamicCommentId();
        DynamicComment dynamicComment = dynamicCommentMapper.selectOneByDynamicCommentId(dynamicCommentId);
        checkDynamicCommentExist(dynamicComment);

        // 检查动态评论所属的动态是否存在
        Integer dynamicId = dynamicComment.getDynamicId();
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(dynamicId);
        checkDynamicExist(dynamic);

        // 检查当前用户是否已点赞过该动态评论回复
        DynamicCommentReplyLove dynamicCommentReplyLove = dynamicCommentReplyLoveMapper.selectOneByUserIdAndDynamicCommentReplyId(userId, dynamicCommentReplyId);
        if (dynamicCommentReplyLove == null) {
            // 用户未点赞过该动态评论回复
            dynamicCommentReplyLove = new DynamicCommentReplyLove();
            dynamicCommentReplyLove.setDynamicCommentReplyId(dynamicCommentReplyId);
            dynamicCommentReplyLove.setStatus(LoveStatus.LOVE);
            dynamicCommentReplyLove.setUserId(userId);

            Integer insert = dynamicCommentReplyLoveMapper.insertOne(dynamicCommentReplyLove);
            if (insert < DatabaseOperationResult.SUCCESS) {
                // 保存到数据库失败
                Result.success(LoveEnum.DYNAMIC_COMMENT_REPLY_FAIL);
            }

            //添加到消息表
            //判断是回复回复的点赞还是评论回复的点赞
            Integer targetDynamicCommentReplyId = dynamicCommentReply.getTargetDynamicCommentReplyId();
            if (targetDynamicCommentReplyId != null) {
                messageService.saveMessage(userId, dynamicCommentReply.getUserId(), dynamicCommentReplyLove.getId(),
                        ModuleType.DYNAMIC_COMMENT_REPLY_LOVE, saveDynamicCommentReplyLoveDTO.getDynamicCommentReplyId(), targetDynamicCommentReplyId, dynamicCommentId, dynamicId);
            } else {
                messageService.saveMessage(userId, dynamicCommentReply.getUserId(), dynamicCommentReplyLove.getId(),
                        ModuleType.DYNAMIC_COMMENT_REPLY_LOVE, null, dynamicCommentReplyId, dynamicCommentId, dynamicId);
            }

        } else if (dynamicCommentReplyLove.getStatus().equals(LoveStatus.LOVE)) {
            // 已点赞该动态评论回复
            ExceptionUtils.error(LoveEnum.DYNAMIC_COMMENT_REPLY_LOVE_LOVED);
        } else {
            // 当前用户点赞过该动态评论回复
            dynamicCommentReplyLove.setStatus(LoveStatus.LOVE);
            Integer update = dynamicCommentReplyLoveMapper.updateDynamicCommentReplyLove(dynamicCommentReplyLove);
            if (update < DatabaseOperationResult.SUCCESS) {
                // 保存到数据库失败
                ExceptionUtils.error(LoveEnum.DYNAMIC_COMMENT_REPLY_FAIL);
            }
            //添加到消息表
            //判断是回复回复的点赞还是评论回复的点赞
            Integer targetDynamicCommentReplyId = dynamicCommentReply.getTargetDynamicCommentReplyId();
            if (targetDynamicCommentReplyId != null) {
                messageService.saveMessage(userId, dynamicCommentReply.getUserId(), dynamicCommentReplyLove.getId(),
                        ModuleType.DYNAMIC_COMMENT_REPLY_LOVE, saveDynamicCommentReplyLoveDTO.getDynamicCommentReplyId(), targetDynamicCommentReplyId, dynamicCommentId, dynamicId);
            } else {
                messageService.saveMessage(userId, dynamicCommentReply.getUserId(), dynamicCommentReplyLove.getId(),
                        ModuleType.DYNAMIC_COMMENT_REPLY_LOVE, null, dynamicCommentReplyId, dynamicCommentId, dynamicId);
            }
        }

        //判断该动态是否为私密,给话题下的热门动态加分
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal()) && dynamic.getTopicId() != null) {
            //非私密给该动态加分
            topicHotDynamicCacheService.addTopicHotDynamicScore(dynamic.getTopicId(), dynamic.getId(), DynamicOperateType.DYNAMIC_REPLY_LOVE);
        }


        // 给用户增加活跃度
        topicUserHotService.addHot(userId, dynamic.getTopicId(), TopicUserHotType.LOVE);

        // 将动态缓存到redis
        dynamicCacheService.saveDynamic2Cache(dynamic, DynamicOperateType.DYNAMIC_LOVE);

        return Result.success();
    }

    /**
     * 检查动态是否不存在或已经被逻辑删除
     *
     * @param dynamic
     */
    private void checkDynamicExist(Dynamic dynamic) {
        if (dynamic == null) {
            // 动态不存在
            ExceptionUtils.error(DynamicEnum.DYNAMIC_NOT_EXIST);
        }
        if (dynamic.getDeleteStatus().equals(DeleteStatus.YES)) {
            // 动态已被删除
            ExceptionUtils.error(DynamicEnum.DYNAMIC_DELETED);
        }
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_PERSONAL).equals(dynamic.getPersonal())) {
            // 动态已设置为匿名
            ExceptionUtils.error(DynamicEnum.DYNAMIC_IS_PERSONAL);
        }
    }

    /**
     * 检查动态评论回复点赞是否真的不存在或者已经被逻辑删除，若是，则会抛出异常
     *
     * @param dynamicCommentReply
     */
    private void checkDynamicCommentReplyExist(DynamicCommentReply dynamicCommentReply) {
        if (dynamicCommentReply == null) {
            // 动态评论回复不存在
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_REPLY_NOT_EXIST);
        }
        if (dynamicCommentReply.getDeleteStatus().equals(DeleteStatus.YES)) {
            // 动态评论回复已删除
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_REPLY_DELETED);
        }
    }

    @Override
    public Result getTotalDynamicList(PageDTO pageDTO) {

        if (pageDTO.getPageNum() < CacheInstruction.LATEST_DYNAMIC_MAX_COUNT / pageDTO.getPageSize()) {
            // 小于 (最大动态缓存量 / 每页数据条数) 的列表，则说明缓存中有存
            PageUtils<Integer> totalDynamicIdPage = dynamicCacheService.getTotalDynamicIdPage(pageDTO);
            List<Integer> dynamicIds = totalDynamicIdPage.getList();
            if (dynamicIds == null || dynamicIds.isEmpty()) {
                return Result.success(totalDynamicIdPage);
            }
            List<TotalDynamicListVo> dynamicVoList = dynamicCacheService.getDynamicVoListFromCache(totalDynamicIdPage);
            return Result.success(PageUtils.restPage(totalDynamicIdPage, dynamicVoList));
        } else {
            // 大于50页的从db拿
            PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
            //查询分页的动态数据
            List<TotalDynamicListPO> dynamicListPoList = dynamicMapper.getTotalDynamicList(pageDTO.getEndIndexId());
            //如果没有动态就直接返回
            if (dynamicListPoList.size() == 0) {
                return Result.success(PageUtils.restPage(new ArrayList<>()));
            }
            List<TotalDynamicListVo> totalDynamicListVoList = getDynamicVoList(dynamicListPoList, pageDTO);
            return Result.success(PageUtils.restPage(dynamicListPoList, totalDynamicListVoList));
        }
    }

    @Override
    public Result getHotDynamicList(PageDTO pageDTO) {
        // 从缓存中获取热门动态的id列表
        PageUtils<Integer> hotDynamicIdPage = dynamicCacheService.getHotDynamicIdPage(pageDTO);
        //获取热门动态id数据
        List<Integer> dynamicIds = hotDynamicIdPage.getList();
        if (dynamicIds == null || dynamicIds.isEmpty()) {
            return Result.success(hotDynamicIdPage);
        }
        //拼装热门动态列表数据
        List<TotalDynamicListVo> dynamicVoList = dynamicCacheService.getDynamicVoListFromCache(hotDynamicIdPage);
        // 分页信息
        return Result.success(PageUtils.restPage(hotDynamicIdPage, dynamicVoList));
    }

    /**
     * 封装动态结果处理逻辑
     *
     * @param list
     * @return
     */
    @Override
    @Deprecated
    public List<TotalDynamicListVo> getDynamicVoList(List<TotalDynamicListPO> list, PageDTO pageDTO) {

        Integer meId = JwtUtils.getMemberIdByJwtToken(request);

        //合并结果到Vo中
        List<TotalDynamicListVo> totalDynamicListVoList = new ArrayList<>();
        for (TotalDynamicListPO totalDynamicListPo : list) {
            TotalDynamicListVo totalDynamicListVo = new TotalDynamicListVo();
            //加入动态id
            int dynamicId = totalDynamicListPo.getId();
            totalDynamicListVo.setId(dynamicId);
            //加入动态内容
            totalDynamicListVo.setContent(totalDynamicListPo.getContent());
            totalDynamicListVo.setStatus(totalDynamicListPo.getStatus());
            totalDynamicListVo.setCreateTime(totalDynamicListPo.getCreateTime());
            totalDynamicListVo.setDynamicPlace(totalDynamicListPo.getDynamicPlace());

            //获取用户信息 考虑用户不存在的情况
            //加入匿名用户信息
            if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(totalDynamicListPo.getStatus())) {
                //从缓存中获取匿名信息
                AnonymousUser anonymousUser = anonyUserService.getAnonymousUserById(totalDynamicListPo.getAnonymousUserId());
                totalDynamicListVo.setAnonymousName(anonymousUser.getAnonymousName());
                totalDynamicListVo.setAnonymousAvatarUrl(anonymousUser.getAnonymousAvatarUrl());
                totalDynamicListVo.setUserId(null);
            } else {
                //否则加入用户信息，从缓存中获取信息并加入
                UserCache userCache = userCacheService.getUserMessageFromUserCacheById(totalDynamicListPo.getUserId());
                totalDynamicListVo.setNickname(userCache.getNickname());
                totalDynamicListVo.setAvatarUrl(userCache.getAvatarUrl());
                totalDynamicListVo.setUserId(userCache.getId());
                // 获取头衔
                UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userCache.getTitleNameId(), userCache.getTitleLogoId());
                totalDynamicListVo.setUserTitlePO(userTitlePo);
            }

            //加入动态图片
            List<DynamicPicturePO> dynamicPictures = pictureCacheService.getDynamicPicturePoFromCache(dynamicId);
            totalDynamicListVo.setDynamicPicturePo(dynamicPictures);

            //加入动态点赞数目 、 评论数目 、转发数目
            DynamicStatistic dynamicStatistic = dynamicCacheService.getDynamicStatistic(dynamicId);
            totalDynamicListVo.setDynamicLoveCount(dynamicStatistic.getLoveCount());
            totalDynamicListVo.setDynamicCommentCount(dynamicStatistic.getCommentCount());
            totalDynamicListVo.setDynamicForwardCount(dynamicStatistic.getForwardCount());



            //加入用户对动态的点赞信息
            boolean flag = userCacheService.getUserDynamicLoveStatusFromCache(meId, dynamicId);
            if (flag){
                totalDynamicListVo.setLoveStatus(LoveStatus.LOVE);
            }else {
                totalDynamicListVo.setLoveStatus(LoveStatus.UN_LOVE);
            }

            //存储用户的关注状态
            boolean flag2 = userCacheService.getUserFollowStatus(meId, totalDynamicListPo.getUserId());
            if (flag2){
                totalDynamicListVo.setFollowStatus(FollowStatus.FOLLOW);
            }else {
                totalDynamicListVo.setFollowStatus(FollowStatus.UN_FOLLOW);
            }

            //添加话题信息, 考虑没有对应话题的情况
             if (totalDynamicListPo.getTopicId() != null && totalDynamicListPo.getTopicId() != 0){
                 Topic topic = topicCacheService.getTopicMessageFromCache(totalDynamicListPo.getTopicId());
                 totalDynamicListVo.setTopicId(topic.getId());
                 totalDynamicListVo.setTitle(topic.getTitle());
             }

            //添加到集合汇总
            totalDynamicListVoList.add(totalDynamicListVo);
        }
        return totalDynamicListVoList;
    }

    @Override
    public Result markDynamicAsPersonal(Integer dynamicId) {

        //查询数据库判断该动态是否属于该主人
        Dynamic dynamic = dynamicMapper.getDynamicById(dynamicId);
        if (dynamic == null) {
            // 动态不存在
            ExceptionUtils.error(DynamicEnum.DYNAMIC_NOT_EXIST);
        }
        if (Short.valueOf(DeleteStatus.YES).equals(dynamic.getDeleteStatus())) {
            // 动态已被删除
            ExceptionUtils.error(DynamicEnum.DYNAMIC_DELETED);
        }
        //判断是否为主人的id
        Integer userId = JwtUtils.getMemberIdByJwtToken(request);
        if (!userId.equals(dynamic.getUserId())) {
            // 无权设置
            ExceptionUtils.error(DynamicEnum.DYNAMIC_UPDATE_NOT_PER);
        }
        //是主人的id
        if (dynamic.getPersonal() == PersonalStatus.VISIBLE_TO_ALL) {
            //原状态为1
            dynamic.setPersonal(PersonalStatus.VISIBLE_TO_PERSONAL);
            //判断动态的状态
            if (dynamic.getTopicId() != null) {
                //删除对应热门动态列表中的key值
                topicHotDynamicCacheService.deleteTopicHotDynamicForMakeAsPersonal(dynamic.getTopicId(), dynamic.getId());
                //删除对应全部动态列表中的key值
                topicAllDynamicCacheService.deleteTopicAllDynamicForMakePersonal(dynamic.getTopicId(), dynamic.getId());
                //删除用户动态列表中缓存的value
                userCacheService.deleteUserAllDynamicForMakePersonal(dynamic.getUserId(), dynamic.getId());
            }
        } else {
            dynamic.setPersonal(PersonalStatus.VISIBLE_TO_ALL);
            //todolist恢复，从私密状态改为正常状态
            if (dynamic.getTopicId() != null) {
                //恢复对应话题下的全部动态的value值
                long timestamp = dynamic.getCreateTime().getTime();
                topicAllDynamicCacheService.recoverTopicAllDynamic(dynamic.getTopicId(), dynamic.getId(), timestamp);
                //恢复对应用户缓存下的全部动态的value
                userCacheService.recoverUserAllDynamic(dynamic.getUserId(), dynamic.getId(), timestamp);
            }
            // 将动态缓存到redis
            dynamicCacheService.saveDynamic2Cache(dynamic, null);
        }
        //更新动态的信息
        Integer integer = dynamicMapper.updateDynamicSecretStatus(dynamicId, dynamic.getPersonal());
        if (integer < DatabaseOperationResult.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_MARK_SECRET_FAIL);
        }
        log.info("【更新成功】：动态私密状态更新成功");
        //删除消息表中的记录(异步）
        List<Short> shorts = Arrays.asList(MessageConstant.DYNAMIC_LIST);
        messageService.deleteMessageByThirdParentId(dynamicId, shorts);
        log.info("【动态相关消息删除成功】：动态消息删除成功");

        // 更新缓存中给的该条动态
        dynamicCacheService.updateDynamicInCache(dynamic);

        return Result.success();
    }

    @Override
    public Result getDynamicListByCondition(PageDTO pageDTO, DynamicSearchConditionDTO dynamicSearchConditionDTO) {
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        //根据条件查询动态信息
        List<TotalDynamicListPO> conditionDynamicList = dynamicMapper.getDynamicListByCondition(dynamicSearchConditionDTO.getEndIndexId(), dynamicSearchConditionDTO.getTopicId(), dynamicSearchConditionDTO.getContent());
        if (conditionDynamicList.size() == 0) {
            return Result.success(PageUtils.restPage(conditionDynamicList));
        }
        List<TotalDynamicListVo> dynamicVoList = getDynamicVoList(conditionDynamicList, pageDTO);
        return Result.success(PageUtils.restPage(conditionDynamicList, dynamicVoList));
    }

    /**
     * 获取评论回复列表
     *
     * @param listCommentReplyDTO
     * @return {@link Result}
     * @author 廖振辉
     */
    @Override
    public Result listCommentReplyByCommentId(ListCommentReplyDTO listCommentReplyDTO) {
        // 判断评论是否存在
        DynamicComment dynamicComment = dynamicCommentMapper.selectOneByDynamicCommentId(listCommentReplyDTO.getCommentId());
        checkDynamicCommentExist(dynamicComment);

        // 判断动态是否存在
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(dynamicComment.getDynamicId());
        checkDynamicExist(dynamic);

        // 获取用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        PageHelper.startPage(listCommentReplyDTO.getPageNum(), listCommentReplyDTO.getPageSize());
        // 获取评论回复列表
        List<DynamicCommentReplyDetailPO> dynamicCommentReplyList = dynamicCommentReplyMapper.selectListByCommentId(dynamicComment.getId());

        // 获取所有回复涉及到的用户id
        // 获取所有回复的用户id
        Set<Integer> userIdSet = dynamicCommentReplyList.stream().map(DynamicCommentReply::getUserId).collect(Collectors.toSet());

        // 获取所有回复的目标回复的用户id
        // 获取所有回复id
        List<Integer> replyIdList = dynamicCommentReplyList.stream().map(DynamicCommentReply::getId).collect(Collectors.toList());
        // 根据回复id获取目标回复用户id
        List<Integer> targetUserIdList = dynamicCommentReplyList.stream()
                .map(DynamicCommentReplyDetailPO::getTargetUserId).collect(Collectors.toList());
        userIdSet.addAll(targetUserIdList);

        // 获取当前用户对回复的点赞状态
        List<Integer> lovedReplyIdList = dynamicCommentReplyLoveMapper.selectListByUserIdAndReply(userId, replyIdList);

        // 统计涉及到的回复的点赞数
        List<ReplyLoveCountPO> replyLoveCountPOList = dynamicCommentReplyLoveMapper.countLoveBatchReplyIds(replyIdList);
        // 建立一个回复id到回复点赞数的映射
        Map<Integer, Integer> replyId2ReplyLoveCountMap = new HashMap<>(replyLoveCountPOList.size());
        for (ReplyLoveCountPO replyLoveCountPO : replyLoveCountPOList) {
            replyId2ReplyLoveCountMap.put(replyLoveCountPO.getReplyId(), replyLoveCountPO.getLoveCount());
        }

        // 动态主人匿名信息
        AnonymousUser anonymousUser = null;

        // 判断动态是否匿名
        if (dynamic.getAnonymousUserId() != null) {
            // 获取匿名信息，覆盖掉动态主人用户的信息
            anonymousUser = anonyUserService.getAnonymousUserById(dynamic.getAnonymousUserId());
        }

        List<DynamicCommentReplyVo> dynamicCommentReplyVos = new ArrayList<>();
        for (DynamicCommentReplyDetailPO dynamicCommentReplyDetailPO : dynamicCommentReplyList) {

            // 回复人信息
//           UserPO userPO = userId2UserPoMap.get(dynamicCommentReplyDetailPO.getUserId());
            //从缓存中获取用户信息
            UserCache userPO = userCacheService.getUserMessageFromUserCacheById(dynamicCommentReplyDetailPO.getUserId());


            // 当前用户对回复的点赞状态
            Short loveStatus = LoveStatus.UN_LOVE;
            if (lovedReplyIdList.contains(dynamicCommentReplyDetailPO.getId())) {
                loveStatus = LoveStatus.LOVE;
            }

            // 目标回复人信息 从缓存中获取用户信息
//            UserPO targetUserPO = userId2UserPoMap.get(dynamicCommentReplyDetailPO.getTargetUserId());
            UserCache targetUserPO = userCacheService.getUserMessageFromUserCacheById(dynamicCommentReplyDetailPO.getTargetUserId());
            TargetReplyUserVO targetReplyUserVO = null;
            if (targetUserPO != null) {
                targetReplyUserVO = new TargetReplyUserVO(targetUserPO.getId(), targetUserPO.getNickname());
                if (targetUserPO.getId().equals(dynamic.getUserId()) && dynamic.getAnonymousUserId() != null) {
                    //如果是匿名就不再获取头衔信息
                    targetReplyUserVO.setUserId(null);
                    if (anonymousUser != null) {
                        targetReplyUserVO.setNickname(anonymousUser.getAnonymousName());
                    } else {
                        targetReplyUserVO.setNickname("匿名信息获取失败");
                    }
                } else {
                    // 获取头衔
                    UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(targetUserPO.getTitleNameId(), targetUserPO.getTitleLogoId());
                    targetReplyUserVO.setUserTitlePO(userTitlePo);
                }
            }


            // 点赞数
            Integer loveCount = replyId2ReplyLoveCountMap.get(dynamicCommentReplyDetailPO.getId());
            if (loveCount == null) {
                loveCount = 0;
            }
            DynamicCommentReplyVo dynamicCommentReplyVo = new DynamicCommentReplyVo(
                    dynamicCommentReplyDetailPO.getId(), dynamicCommentReplyDetailPO.getUserId()
                    , dynamicCommentReplyDetailPO.getCreateTime(), loveCount
                    , loveStatus, dynamicCommentReplyDetailPO.getContent());
            dynamicCommentReplyVo.setTargetReplyUserVO(targetReplyUserVO);
            dynamicCommentReplyVo.setNickname(userPO.getNickname());
            dynamicCommentReplyVo.setAvatarUrl(userPO.getAvatarUrl());
            if (userPO.getId().equals(dynamic.getUserId()) && dynamic.getAnonymousUserId() != null) {
                dynamicCommentReplyVo.setUserId(null);
                if (anonymousUser != null) {
                    dynamicCommentReplyVo.setAvatarUrl(anonymousUser.getAnonymousAvatarUrl());
                    dynamicCommentReplyVo.setNickname(anonymousUser.getAnonymousName());
                } else {
                    dynamicCommentReplyVo.setAvatarUrl("");
                    dynamicCommentReplyVo.setNickname("匿名信息获取失败");
                }
            } else {
                // 获取当前回复主人的头衔
                // 获取头衔
                if (targetUserPO != null){
                    UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(targetUserPO.getTitleNameId(), targetUserPO.getTitleLogoId());
                    dynamicCommentReplyVo.setUserTitlePO(userTitlePo);
                }
            }
            dynamicCommentReplyVos.add(dynamicCommentReplyVo);
        }
        PageUtils<DynamicCommentReplyVo> dynamicCommentReplyVoPage = PageUtils.restPage(dynamicCommentReplyList, dynamicCommentReplyVos);
        return Result.success(dynamicCommentReplyVoPage);
    }


    /**
     * 取消动态评论回复点赞
     *
     * @param dynamicCommentReplyId 动态评论回复id
     * @return
     */
    @Override
    @Transactional
    public Result removeDynamicCommentReplyLove(Integer dynamicCommentReplyId) {
        if (null == dynamicCommentReplyId || dynamicCommentReplyId <= 0) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_REPLY_ID_ERROR);
        }
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        //检验动态评论回复是否存在
        DynamicCommentReply dynamicCommentReply = dynamicCommentReplyMapper.
                selectOneByDynamicCommentReplyId(dynamicCommentReplyId);
        checkDynamicCommentReplyExist(dynamicCommentReply);
        //检验动态评论是否存在
        DynamicComment dynamicComment = dynamicCommentMapper.
                selectOneByDynamicCommentId(dynamicCommentReply.getDynamicCommentId());
        checkDynamicCommentExist(dynamicComment);
        //校验动态是否存在
        Dynamic dynamic = dynamicMapper.
                selectOneByDynamicId(dynamicComment.getDynamicId());
        checkDynamicExist(dynamic);
        //校验动态评论回复点赞是否存在
        DynamicCommentReplyLove dynamicCommentReplyLove = dynamicCommentReplyLoveMapper.
                selectOneByUserIdAndDynamicCommentReplyId(userId, dynamicCommentReplyId);
        if (null == dynamicCommentReplyLove) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_COMMENT_REPLY_NOT_LOVE);
        }
        if (dynamicCommentReplyLove.getStatus().equals(DeleteStatus.NO)) {
            // 动态评论回复点赞已取消
            ExceptionUtils.error(DynamicEnum.LOVE_IS_REMOVE);
        }
        dynamicCommentReplyLove.setStatus(DeleteStatus.NO);
        dynamicCommentReplyLove.setUserId(userId);
        Integer state = dynamicCommentReplyLoveMapper
                .updateDynamicCommentReplyLove(dynamicCommentReplyLove);
        if (state != OperationStatus.SUCCESS) {
            ExceptionUtils.error(DynamicEnum.DELETE_DYNAMIC_COMMENT_REPLY_LOVE_FAILED);
        }
        //删除点赞消息
        messageService.deleteMessage(userId, dynamicCommentReplyLove.getId(), ModuleType.DYNAMIC_COMMENT_REPLY_LOVE);
        return Result.success();
    }

    /**
     * 获取动态详情
     *
     * @param dynamicId 动态id
     * @return
     */
    @Override
    public Result<DynamicDetailVo> getDynamicByDynamicId(Integer dynamicId) {
        if (dynamicId == null || dynamicId <= 0) {
            return new Result(DynamicEnum.DYNAMIC_NOT_EXIST, null);
        }

        Dynamic dynamic = dynamicMapper.getDynamicById(dynamicId);

        if (dynamic == null) {
            return new Result(DynamicEnum.DYNAMIC_NOT_EXIST, null);
        } else if (dynamic.getPersonal() == PersonalStatus.VISIBLE_TO_PERSONAL || dynamic.getDeleteStatus() == DeleteStatus.YES) {
            return new Result(DynamicEnum.DYNAMIC_DELETED, null);
        }

        DynamicDetailVo dynamicDetailVo = new DynamicDetailVo(dynamicId, dynamic.getUserId(), dynamic.getCreateTime(), dynamic.getContent());
        dynamicDetailVo.setTopicId(dynamic.getTopicId());

        //话题存在则
        if (dynamicDetailVo.getTopicId() != 0) {
            dynamicDetailVo.setTitle(topicMapper.getTopicTitleById(dynamicDetailVo.getTopicId()));
        }

        //从缓存中获取用户信息
//        UserPO userPO = userMapper.getUserPartInfoById(dynamic.getUserId());
        UserCache userPO = userCacheService.getUserMessageFromUserCacheById(dynamic.getUserId());
        //用户存在则
        //判断目前是否为匿名状态
        if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(dynamic.getStatus())) {
            //从缓存中获取匿名信息
            AnonymousUser anonymousUser = anonyUserService.getAnonymousUserById(dynamic.getAnonymousUserId());
            dynamicDetailVo.setAnonymousName(anonymousUser.getAnonymousName());
            dynamicDetailVo.setAnonymousAvatarUrl(anonymousUser.getAnonymousAvatarUrl());
            dynamicDetailVo.setStatus(AnonymousStatus.ANONYMOUS);
            dynamicDetailVo.setUserId(null);
        } else {
            if (userPO != null) {
                dynamicDetailVo.setAvatarUrl(userPO.getAvatarUrl());
                dynamicDetailVo.setNickname(userPO.getNickname());
                dynamicDetailVo.setStatus(AnonymousStatus.NORMAL);
                dynamicDetailVo.setUserId(dynamic.getUserId());

                // 设置头衔
                UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userPO.getTitleNameId(), userPO.getTitleLogoId());
                dynamicDetailVo.setUserTitlePO(userTitlePo);
            }
        }

        dynamicDetailVo.setDynamicPicturePo(dynamicPictureMapper.selectAllByDynamicId(dynamicId));
        // 从缓存中获取点赞、评论、转发数
        DynamicStatistic dynamicStatistic = dynamicCacheService.getDynamicStatistic(dynamicId);
        dynamicDetailVo.setDynamicForwardCount(dynamicStatistic.getForwardCount());
        dynamicDetailVo.setDynamicCommentCount(dynamicStatistic.getCommentCount());
        dynamicDetailVo.setDynamicLoveCount(dynamicStatistic.getLoveCount());

        // 获取当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        //点赞状态
        Short loveStatus = dynamicLoveMapper.selectStatusByUserIdAndDynamicId(userId, dynamicId);
        dynamicDetailVo.setLoveStatus(loveStatus);
        FanFollow status = fanFollowMapper.getUserFollowStatus(userId, dynamic.getUserId());
        if (status != null) {
            dynamicDetailVo.setFollowStatus(status.getFollowStatus());
        } else {
            dynamicDetailVo.setFollowStatus(FollowStatus.UN_FOLLOW);
        }

        return new Result<>(CommonEnum.SUCCESS, dynamicDetailVo);
    }

    /**
     * 根据动态id获取 动态评论数+动态下的回复数
     *
     * @param dynamicId 动态id
     * @return {@link Integer} 动态评论数+动态下的回复数
     * @author 廖振辉
     */
    @Override
    public Integer countDynamicCommentAndReply(Integer dynamicId) {
        // 动态下的评论数
//        Integer commentCount =
        return dynamicCommentMapper.countDynamicCommentById(dynamicId, DeleteStatus.NO);
        // 动态下的回复数
//        Integer replyCount = dynamicCommentReplyMapper.countReplyByDynamicId(dynamicId);
//        return commentCount + replyCount;
    }

    /**
     * 新增动态评论Web接口
     *
     * @param saveDynamicCommentDTO 动态评论表单DTO
     * @return 操作状态
     */
    @Override
    @Transactional
    public Result saveDynamicComment(SaveDynamicCommentDTO saveDynamicCommentDTO) {
        log.info("=====开始执行添加动态评论=====");
        // 获取当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        // 判断动态是否存在
        Dynamic dynamic = dynamicMapper.selectOneByDynamicId(saveDynamicCommentDTO.getDynamicId());
        if (dynamic == null) {
            // 动态不存在
            ExceptionUtils.error(DynamicEnum.DYNAMIC_NOT_EXIST);
        }
        if (dynamic.getDeleteStatus().equals(DeleteStatus.YES)) {
            // 动态已被删除
            ExceptionUtils.error(DynamicEnum.DYNAMIC_DELETED);
        }

        // 存储动态评论
        DynamicComment dynamicComment = new DynamicComment();
        dynamicComment.setUserId(userId);
        BeanUtils.copyProperties(saveDynamicCommentDTO, dynamicComment);
        dynamicComment.setDeleteStatus(DeleteStatus.NO);
        Integer save = dynamicCommentMapper.insertDynamicComment(dynamicComment);
        if (save < DatabaseOperationResult.SUCCESS) {
            ExceptionUtils.error(DynamicCommentEnum.DYNAMIC_COMMENT_ADD_FAIL);
        }
        // 封装返回结果
        SaveDynamicCommentVO saveDynamicCommentVO = new SaveDynamicCommentVO();
        saveDynamicCommentVO.setCommentId(dynamicComment.getId());
        saveDynamicCommentVO.setContent(dynamicComment.getContent());

        // 向消息表中插入消息
        log.info("=====插入动态评论消息=====");
        messageService.saveMessage(userId, dynamic.getUserId(), dynamicComment.getId(),
                ModuleType.DYNAMIC_COMMENT, null, null, dynamicComment.getId(), dynamic.getId());
        log.info("=====插入动态评论消息成功=====");
        log.info("=====结束执行添加动态评论=====");

        // 给用户增加活跃度
        topicUserHotService.addHot(userId, dynamic.getTopicId(), TopicUserHotType.COMMENT);

        // 给动态主人加分
        topicUserHotService.addHot(dynamic.getUserId(), dynamic.getTopicId(), TopicUserHotType.BE_COMMENT);


        //判断该动态是否为私密,给话题下的热门动态加分
        if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal()) && dynamic.getTopicId() != null) {
            //非私密给该动态加分
            topicHotDynamicCacheService.addTopicHotDynamicScore(dynamic.getTopicId(), dynamic.getId(), DynamicOperateType.DYNAMIC_COMMENT);
        }

        // 将动态缓存到redis，并加分
        dynamicCacheService.saveDynamic2Cache(dynamic, DynamicOperateType.DYNAMIC_REPLY);

        // 更新缓存中的动态评论数
        dynamicCacheService.updateDynamicCommentCountInCache(dynamicComment);

        return Result.success(saveDynamicCommentVO);
    }

    /**
     * 获取动态评论列表 包括回复
     *
     * @param dynamicId 动态id
     * @return 动态评论列表 包括回复
     */
    @Override
    public Result getDynamicCommentList(Integer dynamicId, PageDTO pageDTO) {
        // 获取当前用户id
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);

        //判断动态是否存在
        Dynamic dynamic = dynamicMapper.getDynamicById(dynamicId);
        if (dynamic == null || dynamic.getDeleteStatus() == 2) {
            ExceptionUtils.error(DynamicEnum.DYNAMIC_NOT_EXIST);
        }
        //是否有权限
        if (dynamic.getPersonal() == 2 && userId.equals(dynamic.getUserId())) {
            ExceptionUtils.error(DynamicEnum.YOU_NOT_POWER);
        }


        //分页查询评论信息
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        //分页查询评论内容
        List<DynamicCommentPo> dynamicCommentPos = dynamicCommentMapper.getDynamicComment(dynamicId);
        //如果评论数目为0
        if (dynamicCommentPos.size() == 0) {
            //没有评论直接返回
            return Result.success(PageUtils.restPage(dynamicCommentPos));
        }

        //查询用户对评论的点赞状态和评论的点赞数目
        //取出所有的评论id
        List<Integer> commentIds = dynamicCommentPos.stream().map(DynamicCommentPo::getCommentId).collect(Collectors.toList());

        //查询评论的点赞数目
        List<DynamicCommentLoveCountPO> dynamicCommentLoveCountPo = dynamicCommentLoveMapper.getDynamicCommentLoveCount(commentIds);
        //建立评论与点赞数的映
        HashMap<Integer, DynamicCommentLoveCountPO> dynamicCommentLoveCountMap = new HashMap<Integer, DynamicCommentLoveCountPO>(20);
        if (dynamicCommentLoveCountPo.size() != 0) {
            for (DynamicCommentLoveCountPO dynamicCommentLoveCountPO : dynamicCommentLoveCountPo) {
                dynamicCommentLoveCountMap.put(dynamicCommentLoveCountPO.getCommentId(), dynamicCommentLoveCountPO);
            }
        }
        //查询用户对该评论的点赞状态
        HashMap<Integer, UserDynamicCommentLovePO> userDynamicCommentLoveStatusMap = new HashMap<>(20);
        List<UserDynamicCommentLovePO> userDynamicCommentLovePo = dynamicCommentLoveMapper.getUserDynamicCommentLoveStatus(userId, commentIds);
        if (userDynamicCommentLovePo.size() != 0) {
            for (UserDynamicCommentLovePO userDynamicCommentLovePO : userDynamicCommentLovePo) {
                userDynamicCommentLoveStatusMap.put(userDynamicCommentLovePO.getDynamicCommentId(), userDynamicCommentLovePO);
            }
        }

        //从缓存中拿出前2条动态回复记录
        List<Integer> replyIdResult = new ArrayList<>();
        for (DynamicCommentPo dynamicCommentPo : dynamicCommentPos) {
            List<Integer> replyIds = dynamicCommentReplyTop5ServiceCache.getTop5ReplyIdByCommentIdFromCache(dynamicCommentPo.getCommentId());
            replyIdResult.addAll(replyIds);
        }

        //根据回复id查询回复的信息
        List<DynamicCommentReplyPo> dynamicCommentReplyList = dynamicCommentReplyMapper.getDynamicCommentReplyByIds(replyIdResult);
        //获取所有的回复的回复id
        List<Integer> tarReplyIds = dynamicCommentReplyList.stream().map(DynamicCommentReplyPo::getTargetDynamicCommentReplyId).collect(Collectors.toList());
        List<DynamicCommentReplyPo> dynamicCommentReply = new ArrayList<>();
        if (tarReplyIds.size() != 0) {
            dynamicCommentReply = dynamicCommentReplyMapper.getDynamicCommentReplyByIds(tarReplyIds);
        }
        //总的回复信息
        dynamicCommentReplyList.addAll(dynamicCommentReply);

        //获取总的回复id
        tarReplyIds.addAll(replyIdResult);

        //查询回复的点赞数目
        List<DynamicCommentReplyLoveCountPO> dynamicCommentReplyLoveCountPo = dynamicCommentReplyLoveMapper.getDynamicCommentReplyLoveCount(tarReplyIds);
        // 建立回复与点赞数的映射
        HashMap<Integer, DynamicCommentReplyLoveCountPO> dynamicCommentReplyLoveCountMap = new HashMap<>(20);
        if (dynamicCommentLoveCountPo.size() != 0) {
            for (DynamicCommentReplyLoveCountPO dynamicCommentReplyLoveCountPO : dynamicCommentReplyLoveCountPo) {
                dynamicCommentReplyLoveCountMap.put(dynamicCommentReplyLoveCountPO.getDynamicCommentReplyId(), dynamicCommentReplyLoveCountPO);
            }
        }
        //建立用户与回复点赞状态的映射
        HashMap<Integer, UserDynamicCommentReplyLoveStatusPO> userDynamicCommentReplyLoveStatusMap = new HashMap<>(20);
        List<UserDynamicCommentReplyLoveStatusPO> userDynamicCommentReplyLoveStatusPo = dynamicCommentReplyLoveMapper.getUserDynamicCommentReplyLoveStatus(userId, replyIdResult);
        if (userDynamicCommentReplyLoveStatusPo.size() != 0) {
            //建立映射
            for (UserDynamicCommentReplyLoveStatusPO userDynamicCommentReplyLoveStatusPO : userDynamicCommentReplyLoveStatusPo) {
                userDynamicCommentReplyLoveStatusMap.put(userDynamicCommentReplyLoveStatusPO.getDynamicCommentReplyId(), userDynamicCommentReplyLoveStatusPO);
            }
        }

        //进行回复信息的匹配,key 是回复id， value是回复DynamicCommentReplyPo, 最多有四十条回复内容
        HashMap<Integer, DynamicCommentReplyPo> replyPoHashMap = new HashMap<>(40);
        for (DynamicCommentReplyPo dynamicCommentReplyPo : dynamicCommentReplyList) {
            replyPoHashMap.put(dynamicCommentReplyPo.getReplyId(), dynamicCommentReplyPo);
        }

        //确定动态用户的信息
        UserPO userPO = new UserPO();

        if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(dynamic.getStatus()) && dynamic.getAnonymousUserId() != null) {
            //用户为匿名用户
            AnonymousUser anonymousUser = anonyUserService.getAnonymousUserById(dynamic.getAnonymousUserId());
            userPO.setNickname(anonymousUser.getAnonymousName());
            userPO.setAvatarUrl(anonymousUser.getAnonymousAvatarUrl());
            userPO.setId(dynamic.getUserId());
        } else {
            //不是匿名用户，从缓存中获取用户信息
            UserCache userCache = userCacheService.getUserMessageFromUserCacheById(dynamic.getUserId());
            userPO.setId(userCache.getId());
            userPO.setNickname(userCache.getNickname());
            userPO.setAvatarUrl(userCache.getAvatarUrl());
            userPO.setTitleLogoId(userCache.getTitleLogoId());
            userPO.setTitleNameId(userCache.getTitleNameId());
        }

        //总的回复数据
        List<DynamicCommentReplyVo> dynamicCommentReplyVo = new ArrayList<>();
        //拼接数据
        for (DynamicCommentReplyPo dynamicCommentReplyPo : dynamicCommentReplyList) {
            DynamicCommentReplyVo dynamicCommentReplyVo1 = new DynamicCommentReplyVo();
            //加入回复的id
            dynamicCommentReplyVo1.setReplyId(dynamicCommentReplyPo.getReplyId());
            //回复人的用户信息
            if (dynamicCommentReplyPo.getUserId().equals(dynamic.getUserId()) && dynamic.getAnonymousUserId() != null) {
                dynamicCommentReplyVo1.setNickname(userPO.getNickname());
                dynamicCommentReplyVo1.setAvatarUrl(userPO.getAvatarUrl());
                dynamicCommentReplyVo1.setUserId(null);
            } else {
                UserCache userCache = userCacheService.getUserMessageFromUserCacheById(dynamicCommentReplyPo.getUserId());
                dynamicCommentReplyVo1.setNickname(userCache.getNickname());
                dynamicCommentReplyVo1.setAvatarUrl(userCache.getAvatarUrl());
                dynamicCommentReplyVo1.setUserId(userCache.getId());

                // 获取头衔
                UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userCache.getTitleNameId(), userCache.getTitleLogoId());
                dynamicCommentReplyVo1.setUserTitlePO(userTitlePo);
            }
            //加入回复时间
            dynamicCommentReplyVo1.setCreateTime(dynamicCommentReplyPo.getCreateTime());

            //回复回复人的用户信息
            DynamicCommentReplyPo dynamicCommentReplyPo1 = replyPoHashMap.get(dynamicCommentReplyPo.getTargetDynamicCommentReplyId());
            TargetReplyUserVO targetReplyUserVO = null;
            if (dynamicCommentReplyPo1 != null && dynamicCommentReplyPo1.getUserId() != null) {
                //获取用户信息
                targetReplyUserVO = new TargetReplyUserVO();
                if (dynamicCommentReplyPo1.getUserId().equals(dynamic.getUserId()) && dynamic.getAnonymousUserId() != null) {
                    //匿名信息
                    targetReplyUserVO.setNickname(userPO.getNickname());
                    targetReplyUserVO.setAvatarUrl(userPO.getAvatarUrl());
                    targetReplyUserVO.setUserId(null);
                } else {
                    UserCache userCache = userCacheService.getUserMessageFromUserCacheById(dynamicCommentReplyPo1.getUserId());
                    targetReplyUserVO.setUserId(userCache.getId());
                    targetReplyUserVO.setNickname(userCache.getNickname());
                    targetReplyUserVO.setAvatarUrl(userCache.getAvatarUrl());
                    // 获取头衔
                    UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userCache.getTitleNameId(), userCache.getTitleLogoId());
                    targetReplyUserVO.setUserTitlePO(userTitlePo);
                }
            }
            dynamicCommentReplyVo1.setTargetReplyUserVO(targetReplyUserVO);
            //获取回复信息
            dynamicCommentReplyVo1.setContent(dynamicCommentReplyPo.getContent());
            //获取用户评论回复点赞状态
            UserDynamicCommentReplyLoveStatusPO userPoStatus = userDynamicCommentReplyLoveStatusMap.get(dynamicCommentReplyPo.getReplyId());
            if (userPoStatus != null) {
                //点赞
                dynamicCommentReplyVo1.setLoveStatus((short) 2);
            }
            //获取回复的总点赞数目
            DynamicCommentReplyLoveCountPO dynamicCommentReplyLoveCountPO = dynamicCommentReplyLoveCountMap.get(dynamicCommentReplyPo.getReplyId());
            if (dynamicCommentReplyLoveCountPO != null) {
                dynamicCommentReplyVo1.setLoveCount(dynamicCommentReplyLoveCountPO.getDynamicCommentReplyLoveCount());
            }
            dynamicCommentReplyVo.add(dynamicCommentReplyVo1);
        }

        //建立评论和回复的映射关系
        HashMap<Integer, DynamicCommentReplyVo> commentAndReplyMap = new HashMap<>(40);
        for (DynamicCommentReplyVo commentReplyVo : dynamicCommentReplyVo) {
            commentAndReplyMap.put(commentReplyVo.getReplyId(), commentReplyVo);
        }

        //总的评论数据
        List<DynamicCommentsVo> dynamicCommentsVos = new ArrayList<>();
        for (DynamicCommentPo dynamicCommentPo : dynamicCommentPos) {
            List<DynamicCommentReplyVo> dynamicCommentReplyVos = new ArrayList<>();
            //创建返回结果对象
            DynamicCommentsVo dynamicCommentsVo = new DynamicCommentsVo();
            //加入评论的用户信息
            if (dynamicCommentPo.getUserId().equals(dynamic.getUserId()) && dynamic.getAnonymousUserId() != null) {
                dynamicCommentsVo.setAvatarUrl(userPO.getAvatarUrl());
                dynamicCommentsVo.setNickname(userPO.getNickname());
                dynamicCommentsVo.setUserId(null);
            } else {
                UserCache userCache = userCacheService.getUserMessageFromUserCacheById(dynamicCommentPo.getUserId());
                dynamicCommentsVo.setUserId(userCache.getId());
                dynamicCommentsVo.setNickname(userCache.getNickname());
                dynamicCommentsVo.setAvatarUrl(userCache.getAvatarUrl());
                // 获取头衔
                UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userCache.getTitleNameId(), userCache.getTitleLogoId());
                dynamicCommentsVo.setUserTitlePO(userTitlePo);
            }
            //加入回复数目
            dynamicCommentsVo.setReplyCount(dynamicCommentPo.getReplyCount());
            //加入评论的id
            dynamicCommentsVo.setCommentId(dynamicCommentPo.getCommentId());
            //加入评论内容
            dynamicCommentsVo.setContent(dynamicCommentPo.getContent());
            //加入评论的时间
            dynamicCommentsVo.setCreateTime(dynamicCommentPo.getCreateTime());

            //给动态评论加入回复
            DynamicCommentReplyVo dynamicCommentReplyVo1 = commentAndReplyMap.get(dynamicCommentPo.getReplyFirstId());
            if (dynamicCommentReplyVo1 != null) {
                dynamicCommentReplyVos.add(dynamicCommentReplyVo1);
            }
            DynamicCommentReplyVo dynamicCommentReplyVo2 = commentAndReplyMap.get(dynamicCommentPo.getReplySecondId());
            if (dynamicCommentReplyVo2 != null) {
                dynamicCommentReplyVos.add(dynamicCommentReplyVo2);
            }
            //加入回复信息
            dynamicCommentsVo.setDynamicCommentReplyVos(dynamicCommentReplyVos);

            //加入评论点赞状态
            UserDynamicCommentLovePO userDynamicCommentLovePO = userDynamicCommentLoveStatusMap.get(dynamicCommentPo.getCommentId());
            if (userDynamicCommentLovePO != null) {
                dynamicCommentsVo.setLoveStatus((short) 2);
            }

            //加入评论点赞数目
            DynamicCommentLoveCountPO dynamicCommentLoveCountPO = dynamicCommentLoveCountMap.get(dynamicCommentPo.getCommentId());
            if (dynamicCommentLoveCountPO != null) {
                dynamicCommentsVo.setLoveCount(dynamicCommentLoveCountPO.getDynamicCommentLoveCount());
            }
            dynamicCommentsVos.add(dynamicCommentsVo);
        }
        return Result.success(PageUtils.restPage(dynamicCommentPos, dynamicCommentsVos));
    }
}
